
class Http {
  constructor() {
    const env = wx.getAccountInfoSync().miniProgram.envVersion;
    console.log(env)
    this.baseUrl = env=="develop"?"https://116.62.181.59":env=="trial"?"https://116.62.181.59":"",
    this.defaultHeader = {
      'Content-Type': 'application/json'
    }
    this.isRefreshing = false // 新增刷新状态标志
    this.requests = [] // 新增请求队列
  }
  setRequestInterceptor(interceptor) {
    this.requestInterceptor = interceptor
  }
  setResponseInterceptor(interceptor) {
    this.responseInterceptor = interceptor
  }
  //封装一个专门上传文件的方法
  uploadFile(options) {
    const { url, filePath, name, formData } = options
    console.log(name)
    const requestOptions = {
      url: this.baseUrl + url,
      filePath: filePath,
      name: name,
      formData: formData,
      header: {
      ...this.defaultHeader,
      ...options.header
      }
    }
    if (this.requestInterceptor) {
      this.requestInterceptor(requestOptions) 
    }
    return new Promise((resolve, reject) => {
      wx.uploadFile({
      ...requestOptions,
        success: res => {
          if (this.responseInterceptor) {
            const response = this.responseInterceptor(res)
          }
          resolve(res)
        },
        fail: err => {
          reject(err)
        }
      }) 
    })
  }
  request(options) {
    const { url, method, data } = options
    const requestOptions = {
      url: this.baseUrl + url,
      method: method || 'GET',
      data: data || {},
      header: {
        ...this.defaultHeader,
        ...options.header
      }
    }

    if (this.requestInterceptor) {
      this.requestInterceptor(requestOptions)  
    } 
    return new Promise((resolve, reject) => {
      wx.request({
        ...requestOptions,
        success: res => {
          if (this.responseInterceptor) {
            const response = this.responseInterceptor(res) 
          }
          resolve(res)
        },
        fail: err => {
          reject(err) 
        }
      }) 
    })
  }
  // 新增 Token 刷新方法
  async refreshToken() {
    wx.request({
      url: this.baseUrl + '/auth/refresh',
      method: 'POST',
      header: {
        Authorization: "Bearer " + wx.getStorageSync('refresh_token'),
      },
      success: res => {
        if (res.statusCode == 200) {
          wx.setStorageSync('access_token', res.data.access_token)
          wx.setStorageSync('refresh_token', res.data.refresh_token)
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  }
  parseJwt(token){
    try {
      // 处理Base64Url编码
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => 
        '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
      ).join(''));
      
      return JSON.parse(jsonPayload);
    } catch (e) {
      return null;
    }
  }
  defaultRequestInterceptor(options) {
    // 从本地存储获取token
    const token = wx.getStorageSync('access_token')
    if (token) {
      options.header = {
        ...options.header,
        Authorization: "Bearer " + token
      }
    }
    
    // 添加 Token 有效期检查（假设 token 有效期为2小时）
    if (token) {
      const payload = this.parseJwt(token);
      if(!payload) return options;
      const expires = payload.exp * 1000
      const remainingTime = expires - Date.now()
      // 有效期不足5分钟时刷新 Token
      if (remainingTime < 300000) { 
        if (!this.isRefreshing) {
          this.isRefreshing = true
          this.refreshToken().finally(() => {
            this.isRefreshing = false
            this.requests.forEach(cb => cb())
            this.requests = []
          })
        }
        
        return new Promise((resolve) => {
          this.requests.push(() => {
            options.header.Authorization = "Bearer " + wx.getStorageSync('access_token')
            resolve(options)
          })
        })
      }
    }
    
    return options
  }
}

// 创建单例实例
const http = new Http()

// 设置默认请求拦截器
http.setRequestInterceptor(http.defaultRequestInterceptor.bind(http))

// 设置全局响应拦截器（示例）
http.setResponseInterceptor(res => {
  if (res.statusCode === 401) {
    wx.removeStorageSync('access_token')
    wx.removeStorageSync('refresh_token')
    wx.reLaunch({ url: '/pages/login/login' })
    return null
  }
  return res.data
})

export default http
